package pers.qianyu.month_202103.date_20210330;

/**
 * 922. 按奇偶排序数组 II
 * https://leetcode-cn.com/problems/sort-array-by-parity-ii/
 *
 * @author mizzle rain
 * @date 2021-03-30 16:35
 */
public class SortArrayByParityII {
    public int[] sortArrayByParityII(int[] nums) {
        int n = nums.length;
        if (n == 0) return new int[0];
        int[] res = new int[n];
        for (int i = 0, p1 = 0, p2 = 1; i < n; i++) {
            if ((nums[i] & 1) == 1) {
                res[p2] = nums[i];
                p2 += 2;
            } else {
                res[p1] = nums[i];
                p1 += 2;
            }
        }
        return res;
    }

    public int[] sortArrayByParityII2(int[] nums) {
        int n = nums.length;
        if (n == 0) return new int[0];
        int p1 = 0, p2 = 1;
        while (p1 < n && p2 < n) {
            while (p1 < n && (nums[p1] & 1) == 0) p1 += 2;
            while (p2 < n && (nums[p2] & 1) == 1) p2 += 2;
            if (p1 < n && (nums[p1] & 1) == 1) {
                int t = nums[p1];
                nums[p1] = nums[p2];
                nums[p2] = t;
            }
        }
        return nums;
    }
}
